﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI.WebControls;

namespace AAA.Web
{
    public class ListBoxHelper
    {
        public static void MoveItem(ListBox lstSource, ListBox lstTarget, MoveTypeEnum eMoveType)
        {
            MoveItem(lstSource, lstTarget, eMoveType, true);
        }

        public static void MoveItem(ListBox lstSource, ListBox lstTarget, MoveTypeEnum eMoveType, bool moveUnique)
        {
            int iInsertIndex = 0;
            List<int> lstSelectedIndex = new List<int>();
            ListBox lstMoveSource = null;
            ListBox lstMoveTarget = null;

            switch (eMoveType)
            {
                case MoveTypeEnum.AddAll:
                    lstMoveSource = lstSource;
                    lstMoveTarget = lstTarget;
                    foreach (ListItem item in lstSource.Items)
                        item.Selected = true;

                    break;
                case MoveTypeEnum.AddSelected:
                    lstMoveSource = lstSource;
                    lstMoveTarget = lstTarget;
                    break;
                case MoveTypeEnum.RemoveAll:
                    lstMoveTarget = lstSource;
                    lstMoveSource = lstTarget;
                    foreach (ListItem item in lstTarget.Items)
                        item.Selected = true;
                    break;
                case MoveTypeEnum.RemoveSelected:
                    lstMoveTarget = lstSource;
                    lstMoveSource = lstTarget;
                    break;
            }

            iInsertIndex = lstMoveTarget.Items.Count;

            for(int i = lstMoveSource.Items.Count - 1; i >= 0; i--)
                if (lstMoveSource.Items[i].Selected)
                {
                    lstSelectedIndex.Add(i);
                }

            for (int i = 0; i < lstSelectedIndex.Count; i++)
            {
                if ((moveUnique == false) || (moveUnique && (lstMoveTarget.Items.IndexOf(lstMoveSource.Items[lstSelectedIndex[i]]) < 0)))
                    lstMoveTarget.Items.Insert(iInsertIndex, lstMoveSource.Items[lstSelectedIndex[i]]);
                lstMoveSource.Items.RemoveAt(lstSelectedIndex[i]);
            }

        }

    }
}
